package cn.com.gome.commons.qcode.generate;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;

import com.gomeplus.frame.utils.StringUtils;
import org.springframework.core.io.UrlResource;

import cn.com.gome.commons.qcode.utils.SFTPUtils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;

/**
 * @ClassName: GenerateQcodeUtil
 * @Description: 二维码生成工具
 * @author shizhengquan
 * @date 2016年3月19日 下午1:43:02
 */
public class GenerateQcodeUtil {

	/**
	* @Title: generateQRCode 
	* @Description: 生成普通二维码或者带logo的二维码 
	* @param content:二维码的内容,例子:http://www.baidu.com
	* @param imgPath:存放的绝对路径,例子:D:\qrcode\
	* @param logoPath:当此参数不为空时候生成带logo的二维码
	* @param pformat:图片的格式
	* @param width:图片宽度大小
	* @param heith:图片高度大小
	* @return  
	* @return String    返回类型 
	* @throws
	 */
	public static String generateQRCode(String content, String imgPath,String logoPath,
			String pformat, int width, int heith,boolean b) {
		
		if (StringUtils.isEmpty(pformat)) {
			pformat = "png";
		}
		String  fileName = UUID.randomUUID()+"."+pformat;
		imgPath = imgPath+fileName;
		try {
			System.out.println(content.length());
			
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
			if(content.length()<110){
				hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//容错率的设置相当重要L,H,M,Q
			}
			hints.put(EncodeHintType.MARGIN, 0);
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			
			BitMatrix bitMatrix = new QRCodeWriter().encode(content,
					BarcodeFormat.QR_CODE, width, heith, hints);
			
			File file = new File(imgPath);
			if(b){
				//去掉白边
				int[] rec = bitMatrix.getEnclosingRectangle();  
				int resWidth = rec[2] + 1;  
				int resHeight = rec[3] + 1;  
				BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);  
				resMatrix.clear();  
				for (int i = 0; i < resWidth; i++) {  
				    for (int j = 0; j < resHeight; j++) {  
				        if (bitMatrix.get(i + rec[0], j + rec[1])) { 
				             resMatrix.set(i, j); 
				        } 
				    }  
				}
				//生成image
				int gwidth = resMatrix.getWidth();
				int gheight = resMatrix.getHeight();
				BufferedImage image = new BufferedImage(gwidth, gheight,BufferedImage.TYPE_INT_ARGB);
				for (int x = 0; x < gwidth; x++) {
				    for (int y = 0; y < gheight; y++) {
				        image.setRGB(x, y, resMatrix.get(x, y) == true ? 
				        Color.BLACK.getRGB():Color.WHITE.getRGB());
				    }
				}
				
				if(StringUtils.isNotEmpty(logoPath)){
					Graphics2D gs = image.createGraphics();
					// 载入logo
					Image img = ImageIO.read(new File(logoPath));
					gs.drawImage(img, gwidth/3+9, gheight/3+9, null);
					gs.dispose();
					img.flush();
				}
				ImageIO.write(image, pformat, file);
			}else{
				//生成image
				int gwidth = bitMatrix.getWidth();
				int gheight = bitMatrix.getHeight();
				BufferedImage image = new BufferedImage(gwidth, gheight,BufferedImage.TYPE_INT_ARGB);
				for (int x = 0; x < gwidth; x++) {
				    for (int y = 0; y < gheight; y++) {
				        image.setRGB(x, y, bitMatrix.get(x, y) == true ? 
				        Color.BLACK.getRGB():Color.WHITE.getRGB());
				    }
				}
				if(StringUtils.isNotEmpty(logoPath)){
					Graphics2D gs = image.createGraphics();
					// 载入logo
					Image img = ImageIO.read(new File(logoPath));
					gs.drawImage(img, gwidth/3+9, gheight/3+9, null);
					gs.dispose();
					img.flush();
				}
				ImageIO.write(image, pformat, file);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("生成普通二维码异常信息:" + e);
			return null;
		}
		return fileName;

	}

	/**
	* @Title: gQRCode 
	* @Description: 生成普通二维码或者带logo的二维码 ,并写到资源服务器上
	* @param content:二维码的内容,例子:http://www.baidu.com
	* @param imgPath:存放到资源服务器上的路径
	* @param logoPath:http访问路径,例子:https://misc.gomein.net.cn/finance/mammon/picture/smgmjr.png
	* @param pformat:图片的格式,例子:png
	* @param width:图片宽度
	* @param heith:图片高度
	* @param ftpIp:上传FTP地址
	* @param ftpPort:端口
	* @param username:用户名
	* @param password:用户密码
	* @param b:是否去掉白边:true去掉，false不去掉
	* @return  
	* @return String    返回类型 
	* @throws
	 */
	public static String gQRCode(String content, String imgPath,String logoPath,
			String pformat, int width, int heith,
			String  ftpIp,	int  ftpPort,String  username,String password,boolean b) throws Exception{
		if (StringUtils.isEmpty(pformat)) {
			pformat = "png";
		}
		String uploadFileName = UUID.randomUUID() + "." + pformat;
		try {
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
			if(content.length()<110){
				hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//容错率的设置相当重要L,H,M,Q
			}
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			hints.put(EncodeHintType.MARGIN, 0);
			
			BitMatrix bitMatrix = new QRCodeWriter().encode(content,
					BarcodeFormat.QR_CODE, width, heith, hints);
				if(b){
					//去掉白边
					int[] rec = bitMatrix.getEnclosingRectangle();  
					int resWidth = rec[2] + 1;  
					int resHeight = rec[3] + 1;  
					BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);  
					resMatrix.clear();  
					for (int i = 0; i < resWidth; i++) {  
					    for (int j = 0; j < resHeight; j++) {  
					        if (bitMatrix.get(i + rec[0], j + rec[1])) { 
					             resMatrix.set(i, j); 
					        } 
					    }  
					}
					//生成image
					int gwidth = resMatrix.getWidth();
					int gheight = resMatrix.getHeight();
					BufferedImage image = new BufferedImage(gwidth, gheight,BufferedImage.TYPE_INT_ARGB);
					for (int x = 0; x < gwidth; x++) {
					    for (int y = 0; y < gheight; y++) {
					        image.setRGB(x, y, resMatrix.get(x, y) == true ? 
					        Color.BLACK.getRGB():Color.WHITE.getRGB());
					    }
					}
					
					if(StringUtils.isNotEmpty(logoPath)){
						Graphics2D gs = image.createGraphics();
						// 载入logo
						URL u = new URL(logoPath);
						UrlResource ur = new UrlResource(u);
						InputStream in = ur.getInputStream();
						Image img = ImageIO.read(in);
						gs.drawImage(img, gwidth/3+9, gheight/3+9, null);
						gs.dispose();
						img.flush();
						in.close();
					}
					//上传到静态资源服务器上
					ByteArrayOutputStream os = new ByteArrayOutputStream();  
					ImageIO.write(image, pformat, os);  
					InputStream is = new ByteArrayInputStream(os.toByteArray()); 
					ChannelSftp sftp = null;
					sftp = SFTPUtils.connect(ftpIp, ftpPort, username, password, null, null, 3000);  //sftp连接
				 	try{
					    sftp.cd(imgPath);
				     }catch(SftpException sException){
					    if(ChannelSftp.SSH_FX_NO_SUCH_FILE == sException.id){
					    	sftp.mkdir(imgPath);
					        sftp.cd(imgPath);
					    }
				     }
					boolean flag = SFTPUtils.upload(uploadFileName,is,sftp, ChannelSftp.OVERWRITE);
					if(!flag){
						return null;
					}
					os.close();
					is.close();
					
				}else{
					
					//生成image
					int gwidth = bitMatrix.getWidth();
					int gheight = bitMatrix.getHeight();
					BufferedImage image = new BufferedImage(gwidth, gheight,BufferedImage.TYPE_INT_ARGB);
					for (int x = 0; x < gwidth; x++) {
					    for (int y = 0; y < gheight; y++) {
					        image.setRGB(x, y, bitMatrix.get(x, y) == true ? 
					        Color.BLACK.getRGB():Color.WHITE.getRGB());
					    }
					}
					
					if(StringUtils.isNotEmpty(logoPath)){
						Graphics2D gs = image.createGraphics();
						// 载入logo
						URL u = new URL(logoPath);
						UrlResource ur = new UrlResource(u);
						InputStream in = ur.getInputStream();
						Image img = ImageIO.read(in);
						gs.drawImage(img, gwidth/3+9, gheight/3+9, null);
						gs.dispose();
						img.flush();
						in.close();
					}
					//上传到静态资源服务器上
					ByteArrayOutputStream os = new ByteArrayOutputStream();  
					ImageIO.write(image, pformat, os);  
					InputStream is = new ByteArrayInputStream(os.toByteArray()); 
					ChannelSftp sftp = null;
					sftp = SFTPUtils.connect(ftpIp, ftpPort, username, password, null, null, 0);  //sftp连接
				 	try{
					    sftp.cd(imgPath);
				     }catch(SftpException sException){
					    if(ChannelSftp.SSH_FX_NO_SUCH_FILE == sException.id){
					    	sftp.mkdir(imgPath);
					        sftp.cd(imgPath);
					    }
				     }
					boolean flag = SFTPUtils.upload(uploadFileName,is,sftp, ChannelSftp.OVERWRITE);
					if(!flag){
						return null;
					}
					os.close();
					is.close();
				}
		} catch (Exception e) {
			System.out.println("生成二维码异常信息:" + e);
			throw new Exception("生成二维码异常信息!");
		}
		return uploadFileName;

	}

	public static void main(String[] args) {
		try {
			
			String  ftpIp = "10.58.52.45";
			int  ftpPort = 22;
			String  username = "jenkins";
			String 	password = "jenkins";
//			String path =	gQRCode("http://baina.gome.com.cn","/app/finance/mammon/orcode",
//					"https://misc.gomein.net.cn/finance/mammon/picture/smgmjr.png",null,180,180
//				,ftpIp,ftpPort,username,password,false);
//		System.out.println(path);
		
		//			generateCodeImage("http://www.baidu.com?abcd=1122323333dafaafafagagagagagagfaqfag","D:\\qrcode\\","D:\\qrcode\\smgmjr.png",null,300,300);
//		String path =	generateQRCode("http://www.baidu.com", "D:\\qrcode\\","D:\\qrcode\\smgmjr.png",null, 300, 300);
			//http://m.atguat.com.cn/finance_active.html?qrcodeId=2EEE54C1435206CEE0507E0AC5356905
			String path =	generateQRCode("http://m.atguat.com.cn/finance_activessssssssssssssssssssssssssfinance_activessssssssssssssssssssssssss.html?qrcodeId=2EEE54C1435206CEE0507E0AC5356905", "D:\\qrcode\\","D:\\qrcode\\smgmjr.png",null, 180, 180,false);
			System.out.println(path);
			String str = "";
//		
//		for(int i=0;i<29;i++){
//			str = str+"abcdefgh";
//			
//			String path =	generateQRCode("http://www.baidu.com?abcd="+str, "10.58.52.45:/app/finance/mammon/orcode",null,null, 300, 300);
//			System.out.println("生成图片路径:"+path+",第"+i+"次");
//		}
		
//		for(int i=0;i<29;i++){
//			str = str+"abcdefgh";
//			
//			String path =	generateQRCode("http://www.baidu.com?abcd="+str, "D:\\qrcode\\","D:\\qrcode\\smgmjr.png",null, 180, 180,false);
//			System.out.println("生成图片路径:"+path+",第"+i+"次");
//		}
		
//		 UUID uuid = UUID.randomUUID();
//		 System.out.println(uuid);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e);
		}
		
	}

}
